package com.mashibing.monitor.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @author SNA
 * @date 2025/10/22
 * @Description 邮件发送工具类，用于发送HTML格式的邮件
 **/
@Component
@RefreshScope
public class MailUtil {

    @Value("${spring.mail.username}")
    private String from;

    @Value("${spring.mail.tos}")
    private String tos;

    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * 发送邮件方法
     * @param subject 邮件主题
     * @param text 邮件内容文本
     * @throws MessagingException 邮件发送异常
     */
    public void sendEmail(String subject, String text) throws MessagingException {

        // 创建MIME邮件消息对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();

        // 创建邮件助手类，用于设置邮件属性
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
        helper.setFrom(from);
        helper.setTo(tos.split(","));
        helper.setSubject(subject);
        helper.setText(text);

        // 发送邮件
        javaMailSender.send(mimeMessage);
    }


    /**
     * 发送邮件方法重载
     * @param to 收件人邮箱地址
     * @param subject 邮件主题
     * @param text 邮件正文内容
     * @throws MessagingException 邮件发送异常
     */
    public void sendEmail(String to, String subject, String text) throws MessagingException {

        // 创建MIME邮件消息对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();

        // 创建邮件助手类，用于设置邮件属性
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(text);

        // 发送邮件
        javaMailSender.send(mimeMessage);
    }
}
